// 导入ws模块
const WebSocket = require("ws");

// 创建一个WebSocket服务器，绑定到 port 端口
const wss = new WebSocket.Server({ noServer: true });

const data = {
  "1_3_5": "50",
  // "1_3_12": "66",
};

// 当有客户端连接时触发
wss.on("connection", (ws) => {
  // 接收客户端发来的消息
  ws.on("message", (message) => {
    // 如果 message 开头为 ping 终止
    if (message == "ping") return;
    const messageString = String(message);
    if (typeof messageString === "string") {
      const [key, value] = messageString.split(" ");
      if (key && value) {
        data[key] = value;
      }
    }
  });
  onSendClientData();

  // 当连接关闭时触发
  ws.on("close", () => {
    console.log("客户端已断开连接");
  });
});

// 发送消息
function broadcast(message) {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(message);
    }
  });
}

function onSendClientData() {
  for (const key in data) {
    if (Object.hasOwnProperty.call(data, key)) {
      const value = data[key];
      broadcast(`${key} ${value}`);
    }
  }
}

// 设置定时器，每隔指定的时间（例如，每5秒）向所有客户端发送消息
const interval = setInterval(() => {
  onSendClientData();
}, 5 * 1000); // ms

// 添加一个监听器以优雅地处理程序退出，清除定时器
process.on("SIGINT", function () {
  clearInterval(interval);
  console.log("\nGracefully shutting down from SIGINT (Ctrl-C)");
  process.exit();
});

module.exports = wss;
